package com.camartsApp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camartsApp.service.UserService;
import com.camartsApp.Util.JwtUtils;
import com.camartsApp.Util.RedisUtil;
import com.camartsApp.entity.User;
import com.camartsApp.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * @version .......
 * @创建时间 2025/6/12  下午4:16
 * @创建者 玉苏甫江
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtils jwtUtils;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    // token过期时间，单位：秒（可根据实际需要调整）
    private static final long TOKEN_EXPIRE_SECONDS = 60 * 60*24 ; // 24小时

    @Override
    public String register(User user) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone", user.getPhone());
        if (userMapper.selectOne(query) != null) {
            return "手机号已被注册";
        }
        if (user.getEmail() != null && !user.getEmail().isEmpty()) {
            QueryWrapper<User> emailQw = new QueryWrapper<>();
            emailQw.eq("email", user.getEmail());
            if (userMapper.selectOne(emailQw) != null) {
                return "邮箱已被注册";
            }
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setAvatar("https://img.52tiemo.com/uploads/allimg/210526/3-210526154U5-50.jpg");
        int result = userMapper.insert(user);
        return result > 0 ? "注册成功" : "注册失败";
    }

    @Override
    public String login(String phone, String password) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone", phone);
        User user = userMapper.selectOne(query);
        if (user == null) {
            return "手机号错误或不存在";
        }
        if (user.getStatus() != 0) {
            return "该账号已被封禁";
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return "密码错误";
        }
        String token = jwtUtils.generateToken(user.getId(), user.getPhone());
        // 保存token到Redis，key为 user:{phone}:token（String类型），并设置过期时间
        String redisKey = "usert:" + user.getPhone() + ":token";
        redisUtil.set(redisKey, token, TOKEN_EXPIRE_SECONDS);
        return token;
    }

    @Override
    public void logout(String phone) {
        String redisKey = "usert:" + phone + ":token";
        redisUtil.delete(redisKey);
    }

    @Override
    public User getUserInfo(String phone) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone", phone);
        User user = userMapper.selectOne(query);
        if (user != null) {
            user.setPassword(null);
        }
        return user;
    }

    @Override
    public boolean updateAvatar(String phone, String avatarUrl) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone", phone);
        User user = userMapper.selectOne(query);
        if (user == null) return false;
        user.setAvatar(avatarUrl);
        return userMapper.updateById(user) > 0;
    }

    @Override
    public boolean updatePassword(String phone, String oldPassword, String newPassword, String token) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone", phone);
        User user = userMapper.selectOne(query);
        if (user == null) {
            System.out.println("DEBUG: updatePassword failed - 用户不存在: " + phone);
            return false;
        }
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            System.out.println("DEBUG: updatePassword failed - 密码错误 for phone: " + phone);
            return false;
        }
        user.setPassword(passwordEncoder.encode(newPassword));
        int result = userMapper.updateById(user);
        if (result > 0) {
            System.out.println("DEBUG: updatePassword success for phone: " + phone);
            return true;
        }
        System.out.println("DEBUG: updatePassword failed - 数据库更新失败 for phone: " + phone);
        return false;
    }

    @Override
    public User updatePhone(String oldPhone, String password, String newPhone, String token) {
        if (newPhone == null || newPhone.isEmpty()) return null;
        QueryWrapper<User> newQw = new QueryWrapper<>();
        newQw.eq("phone", newPhone);
        if (userMapper.selectOne(newQw) != null) {
            return null;
        }
        QueryWrapper<User> oldQw = new QueryWrapper<>();
        oldQw.eq("phone", oldPhone);
        User user = userMapper.selectOne(oldQw);
        if (user == null) return null;
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return null;
        }
        user.setPhone(newPhone);
        int result = userMapper.updateById(user);
        if (result > 0) {
            String oldRedisKey = "usert:" + oldPhone + ":token";
            String redisToken = redisUtil.get(oldRedisKey);
            if (redisToken != null && redisToken.equals(token)) {
                redisUtil.delete(oldRedisKey);
            }
            String newToken = jwtUtils.generateToken(user.getId(), newPhone);
            String newRedisKey = "usert:" + newPhone + ":token";
            redisUtil.set(newRedisKey, newToken, TOKEN_EXPIRE_SECONDS);
            System.out.println("DEBUG: User object phone after update in UserServiceImpl: " + user.getPhone());
            return user;
        }
        return null;
    }

    @Override
    public boolean updateUserInfo(User user) {
        if (user == null || user.getPhone() == null) {
            return false;
        }
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone", user.getPhone());
        User dbUser = userMapper.selectOne(query);
        if (dbUser == null) {
            return false;
        }
        // 只允许修改部分字段
        dbUser.setNickname(user.getNickname());
        dbUser.setSignature(user.getSignature());
        return userMapper.updateById(dbUser) > 0;
    }

    @Override
    public boolean updateEmail(String phone, String password, String newEmail) {
        if (newEmail == null || newEmail.isEmpty()) {
            System.out.println("DEBUG: updateEmail failed - 新邮箱不能为空 for phone: " + phone);
            return false;
        }
        QueryWrapper<User> emailQw = new QueryWrapper<>();
        emailQw.eq("email", newEmail);
        if (userMapper.selectOne(emailQw) != null) {
            System.out.println("DEBUG: updateEmail failed - 新邮箱已被注册: " + newEmail + " for phone: " + phone);
            return false;
        }
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone", phone);
        User user = userMapper.selectOne(query);
        if (user == null) {
            System.out.println("DEBUG: updateEmail failed - 用户不存在 for phone: " + phone);
            return false;
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            System.out.println("DEBUG: updateEmail failed - 密码错误 for phone: " + phone);
            return false;
        }
        user.setEmail(newEmail);
        int result = userMapper.updateById(user);
        if (result > 0) {
            System.out.println("DEBUG: updateEmail success for phone: " + phone);
            return true;
        }
        System.out.println("DEBUG: updateEmail failed - 数据库更新失败 for phone: " + phone);
        return false;
    }

    @Override
    public User getUserInfoByPhone(String phone) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone", phone);
        User user = userMapper.selectOne(query);
        if (user != null) {
            user.setPassword(null);
        }
        return user;
    }
}